package com.eastfair.transport.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.common.dto.AttachmentFileDTO;
import com.eastfair.common.vo.AttachmentFileVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.pay.api.AttachmentFileFeign;
import com.eastfair.transport.dao.CustomsClearanceMapper;
import com.eastfair.transport.dto.CustomsClearanceDTO;
import com.eastfair.transport.dto.CustomsClearancePageQuery;
import com.eastfair.transport.entity.CustomsClearance;
import com.eastfair.transport.enums.MainTransportModuleEnum;
import com.eastfair.transport.service.CustomsClearanceService;
import com.eastfair.transport.vo.CustomsClearanceVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 清关商品
 * </p>
 *
 * @author linan
 * @date 2022-07-21
 */
@Slf4j
@Service
public class CustomsClearanceServiceImpl extends SuperServiceImpl<CustomsClearanceMapper, CustomsClearance> implements CustomsClearanceService {

    @Resource
    private AttachmentFileFeign attachmentFileFeign;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<CustomsClearance> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }


    @Override
    protected R<Boolean> handlerSave(CustomsClearance model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> addCustomsClearance(CustomsClearanceDTO customsClearanceDTO) {
        CustomsClearance customsClearance = BeanUtil.copyProperties(customsClearanceDTO, CustomsClearance.class);
        boolean save = save(customsClearance);
        saveCustomsClearanceFiles(customsClearanceDTO, customsClearance);
        return R.success(save);
    }

    private void saveCustomsClearanceFiles(CustomsClearanceDTO customsClearanceDTO, CustomsClearance customsClearance) {
        // 处理各类图片
        List<AttachmentFileDTO> attachmentFiles = new ArrayList<>(16);
        // 报关单
        attachmentFiles.addAll(saveFile(customsClearance, customsClearanceDTO.getCustomsDeclarationFiles(), MainTransportModuleEnum.CUSTOMS_DECLARATION_FILES.getCode()));
        // 托运单
        attachmentFiles.addAll(saveFile(customsClearance, customsClearanceDTO.getConsignmentNoteFiles(), MainTransportModuleEnum.CONSIGNMENT_NOTE_FILES.getCode()));
        // 发票
        attachmentFiles.addAll(saveFile(customsClearance, customsClearanceDTO.getInvoiceFiles(), MainTransportModuleEnum.INVOICE_FILES.getCode()));
        // 贸易合同
        attachmentFiles.addAll(saveFile(customsClearance, customsClearanceDTO.getTradeContractFiles(), MainTransportModuleEnum.TRADE_CONTRACT_FILES.getCode()));
        // 出口收汇核算单
        attachmentFiles.addAll(saveFile(customsClearance, customsClearanceDTO.getExportCollectionFiles(), MainTransportModuleEnum.EXPORT_COLLECTION_FILES.getCode()));
        // 海关监管证件
        attachmentFiles.addAll(saveFile(customsClearance, customsClearanceDTO.getCustomsSupervisionCertificateFiles(), MainTransportModuleEnum.CUSTOMS_SUPERVISION_CERTIFICATE_FILES.getCode()));
        // 其他附件
        attachmentFiles.addAll(saveFile(customsClearance, customsClearanceDTO.getOtherFiles(), MainTransportModuleEnum.OTHER_FILES.getCode()));
        if(CollectionUtils.isNotEmpty(attachmentFiles)){
            attachmentFileFeign.addAttachmentFile(attachmentFiles);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> updateCustomsClearance(CustomsClearanceDTO customsClearanceDTO) {
        CustomsClearance customsClearance = BeanUtil.copyProperties(customsClearanceDTO, CustomsClearance.class);
        boolean result = updateById(customsClearance);
        // 删除原附件
        removeFiles(customsClearance.getId());
        // 添加新的附件
        saveCustomsClearanceFiles(customsClearanceDTO, customsClearance);
        return R.success(result);
    }

    @Override
    public R<IPage<CustomsClearanceVO>> queryCustomsClearance(PageParams<CustomsClearancePageQuery> customsClearancePageQuery) {
        Page<CustomsClearance> buildPage = customsClearancePageQuery.buildPage();
        CustomsClearancePageQuery model = customsClearancePageQuery.getModel();
        // 返回结果VO
        Page<CustomsClearanceVO> result = customsClearancePageQuery.buildPage();
        // 封装查询条件
        LambdaQueryWrapper<CustomsClearance> wrapper = new QueryWrapper<CustomsClearance>().lambda().eq(Objects.nonNull(model.getExhibitionManageId()),CustomsClearance::getExhibitionManageId,model.getExhibitionManageId()).orderByDesc(CustomsClearance::getCreateTime);
        Page<CustomsClearance> page = page(buildPage, wrapper);
        BeanUtil.copyProperties(page, result);
        List<CustomsClearance> records = page.getRecords();
        ArrayList<CustomsClearanceVO> resultList = new ArrayList<>();
        // 遍历处理VO
        for (CustomsClearance record : records) {
            CustomsClearanceVO customsClearanceVO = BeanUtil.copyProperties(record, CustomsClearanceVO.class);
            R<List<AttachmentFileVO>> listR = attachmentFileFeign.queryAttachmentFile(AttachmentFileDTO.builder().businessId(record.getId()).build());
            List<AttachmentFileVO> data = listR.getData();
            if(CollectionUtils.isNotEmpty(data)){
                Map<String, List<AttachmentFileVO>> collect = data.stream().collect(Collectors.groupingBy(AttachmentFileVO::getBusinessType));
                customsClearanceVO.setCustomsDeclarationFiles(collect.get(MainTransportModuleEnum.CUSTOMS_DECLARATION_FILES.getCode()));
                customsClearanceVO.setConsignmentNoteFiles(collect.get(MainTransportModuleEnum.CONSIGNMENT_NOTE_FILES.getCode()));
                customsClearanceVO.setInvoiceFiles(collect.get(MainTransportModuleEnum.INVOICE_FILES.getCode()));
                customsClearanceVO.setTradeContractFiles(collect.get(MainTransportModuleEnum.TRADE_CONTRACT_FILES.getCode()));
                customsClearanceVO.setExportCollectionFiles(collect.get(MainTransportModuleEnum.EXPORT_COLLECTION_FILES.getCode()));
                customsClearanceVO.setCustomsSupervisionCertificateFiles(collect.get(MainTransportModuleEnum.CUSTOMS_SUPERVISION_CERTIFICATE_FILES.getCode()));
                customsClearanceVO.setOtherFiles(collect.get(MainTransportModuleEnum.OTHER_FILES.getCode()));
                resultList.add(customsClearanceVO);
            }
        }
        result.setRecords(resultList);
        return R.success(result);
    }

    @Override
    public Boolean delCustomsClearance(List<CustomsClearanceDTO> customsClearanceDTO) {

        for (CustomsClearanceDTO customsClearance : customsClearanceDTO) {
            // 删除原附件
            removeFiles(customsClearance.getId());
        }
        return removeByIdsOfLogic(ConvertUtil.convertList(customsClearanceDTO,CustomsClearance.class));
    }

    /**
     * 移除附件
     * @param customsClearance customsClearance
     */
    private void removeFiles(Long customsClearance) {
        R<List<AttachmentFileVO>> listR = attachmentFileFeign.queryAttachmentFile(AttachmentFileDTO.builder().businessId(customsClearance).build());
        List<AttachmentFileVO> data = listR.getData();
        if(CollectionUtils.isNotEmpty(data)){
            attachmentFileFeign.deteleBatch(data.stream().map(AttachmentFileVO::getId).collect(Collectors.toList()));
        }
    }

    /**
     * 保存文件
     * @param customsClearance customsClearance
     * @param files files
     * @param code code
     * @return List<AttachmentFileDTO>
     */
    private List<AttachmentFileDTO> saveFile(CustomsClearance customsClearance, List<AttachmentFileDTO> files, String code) {
        if(CollectionUtils.isNotEmpty(files)){
            for (AttachmentFileDTO customsDeclarationFile : files) {
                customsDeclarationFile.setBusinessType(code);
                customsDeclarationFile.setBusinessId(customsClearance.getId());
            }
        }
        return files;
    }
}
